package com.fly.demo.files;

import java.io.File;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.junit.jupiter.api.Test;

public class FileListByApache
{
    String path = System.getenv().get("USERPROFILE") + "\\Pictures\\";
    
    File searchFile = new File(path);
    
    /**
     * 遍历文件目录
     * 
     */
    @Test
    public void testListFilesAndDirs001()
    {
        Collection<File> files = FileUtils.listFilesAndDirs(searchFile, new NotFileFilter(TrueFileFilter.TRUE), DirectoryFileFilter.DIRECTORY);
        files.stream().forEach(System.out::println);
    }
    
    /**
     * 遍历文件目录
     * 
     */
    @Test
    public void testListFilesAndDirs002()
    {
        Collection<File> files = FileUtils.listFilesAndDirs(searchFile, TrueFileFilter.TRUE, DirectoryFileFilter.DIRECTORY);
        files.stream().forEach(System.out::println);
    }
    
    /**
     * 遍历文件
     * 
     */
    @Test
    public void testListFiles001()
    {
        // 搜索子目录
        Collection<File> pics = FileUtils.listFiles(searchFile, new String[] {"jpg", "png"}, true);
        pics.stream().forEach(System.out::println);
        
        // 搜索子目录
        Collection<File> pngs = FileUtils.listFiles(searchFile, FileFilterUtils.suffixFileFilter("png"), TrueFileFilter.INSTANCE);
        pngs.stream().forEach(System.out::println);
    }
    
    /**
     * 遍历文件
     * 
     */
    @Test
    public void testListFiles002()
    {
        // 不搜索子目录
        Collection<File> pics = FileUtils.listFiles(searchFile, new String[] {"jpg", "png"}, false);
        pics.stream().forEach(System.out::println);
        
        // 不搜索子目录
        Collection<File> pngs = FileUtils.listFiles(searchFile, FileFilterUtils.suffixFileFilter("png"), null);
        pngs.stream().forEach(System.out::println);
    }
    
    /**
     * 遍历文件
     * 
     */
    @Test
    public void testListFiles003()
    {
        // 下面用法区别?
        AtomicInteger count = new AtomicInteger();
        FileUtils.listFiles(searchFile, TrueFileFilter.TRUE, DirectoryFileFilter.DIRECTORY).stream().peek(f -> System.out.print(count.incrementAndGet() + ".\t")).forEach(System.out::println);
        
        count.set(0);
        FileUtils.listFiles(searchFile, TrueFileFilter.TRUE, TrueFileFilter.INSTANCE).stream().peek(f -> System.out.print(count.incrementAndGet() + ".\t")).forEach(System.out::println);
    }
}
